package org.methodbox.extractor;

import java.io.BufferedReader;
import java.io.BufferedWriter;
import java.io.File;
import java.io.FileInputStream;
import java.io.FileNotFoundException;
import java.io.FileReader;
import java.io.FileWriter;
import java.io.IOException;
import java.io.InputStreamReader;
import java.io.Reader;
import java.io.Writer;
import java.util.logging.Level;
import java.util.logging.Logger;
import java.util.zip.ZipEntry;
import java.util.zip.ZipInputStream;

/**
 *
 * @author Christian
 */
public class Unpacker {

    private BufferedReader input;

    private BufferedWriter[] outWriters;

    private String[] columnNames;

    private int start = 0;

    private int numColumns;

    private void openInput(File inputFile) throws ExtractorException{
        try {
            if (inputFile.getName().toLowerCase().endsWith(".zip")){
                FileInputStream raw = new FileInputStream(inputFile);
                ZipInputStream zip = new ZipInputStream(raw);
                ZipEntry entry = zip.getNextEntry();
                input = new BufferedReader (new InputStreamReader(zip));
            } else {
                input = new BufferedReader (new FileReader(inputFile));
            }
        } catch (IOException ex) {
            throw new ExtractorException(ex);
        }
    }

    private String scrub(String name){
        String scrubbed = name.toLowerCase();
        scrubbed = scrubbed.replace("\"", "");
        return scrubbed;
    }

    private void openOutput(File outputDir) throws ExtractorException{
        try {
            String headLine = input.readLine();
            columnNames = headLine.split("\t");
            numColumns = columnNames.length;
            outWriters = new BufferedWriter[numColumns];
            for (int i = 0; i<numColumns; i++){
                File outputFile = new File (outputDir,scrub(columnNames[i])+".txt");
                outWriters[i] = new BufferedWriter(new FileWriter(outputFile));
            }
        } catch (IOException ex) {
            throw new ExtractorException(ex);
        //} catch (FileNotFoundException ex) {
        //    throw new ExtractorException(ex);
        }
    }

    private void close() throws ExtractorException{
        try {
            input.close();
            for (int i = 0; i<numColumns; i++){
                outWriters[i].close();
            }
        } catch (IOException ex) {
             throw new ExtractorException(ex);
        }
    }

    public Unpacker(){
    }

    public void run(String inputDirName) throws ExtractorException{
        File inputDir = new File(inputDirName);
        File[] inputFiles = inputDir.listFiles();
        for (int i = 0; i< inputFiles.length; i++){
            if (inputFiles[i].isFile()){
                String fileName = inputFiles[i].getName();
                int pos = fileName.indexOf('.');
                if (pos > 0){
                    String dirName = fileName.substring(0, pos);
                    File directory = new File(inputDir, dirName);
                    if (directory.exists()){
                        if (directory.isFile()){
                            throw new ExtractorException("Found a file in tagret directory location " +
                                directory.getAbsolutePath());
                        } else {
                            System.out.println ("Ignoring "+fileName);
                        }
                    } else {
                        directory.mkdirs();
                        splitFile (inputFiles[i], directory);
                    }
                }
             }
        }
    }

    public void splitFile(File inputFile, File outputDir) throws ExtractorException{
        try {
            System.out.println("Spliting "+inputFile.getAbsolutePath());
            openInput(inputFile);
            openOutput(outputDir);
            while (input.ready()) {
                String inputLine = input.readLine();
                String[] inputs = inputLine.split("\t");
                for (int i = 0; i<numColumns; i++){
                    outWriters[i].write(inputs[i+start]+"\n");
                }
            }
        } catch (IOException ex) {
             throw new ExtractorException(ex);
        }
       close();
    }

    public static void main( String[] args ) throws ExtractorException
    {
        //tring inputFileName = "C:/Ruby/elab/java/extractor/Data/small.data";
        //tring columnsToPick = "Afford4,Amthb";
        String inputFileName = "C:/elabs/csv";
        Unpacker parser = new Unpacker();
        parser.run(inputFileName);
    }

}
